package com.freewater.javabase.demo.network.netaddress;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddressDemo {
    public static void main(String[] args) {
        try {
            // 不就会设置内部的是有字段存储host，而且会链接dns服务器找到一个对应的ip地址，否则抛出UnknownHostException异常
            InetAddress inetAddress = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress);// www.baidu.com/180.101.49.42
            // 反查域名
            inetAddress = InetAddress.getByName("180.101.49.41");
            System.out.println(inetAddress.getHostName()); // www.baidu.com
            // 获取所有的IP地址
            for (InetAddress address : InetAddress.getAllByName("www.baidu.com")) {
                System.out.println(address);
            }
            // 获取本地InetAddress
            inetAddress = InetAddress.getLocalHost();
            System.out.println(inetAddress);
            // 通过ip地址构建InetAddress，无需dns服务器查询
            inetAddress = InetAddress.getByAddress(new byte[]{(byte)192,(byte)168,1,1});
            System.out.println(inetAddress);
            // 通过ip地址和主机名构建InetAddress，无需dns服务器查询
            inetAddress = InetAddress.getByAddress("myhost", new byte[]{(byte) 192, (byte) 168, 1, 1});
            System.out.println(inetAddress);
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }
}
